package cn.js.sangu.unitStore.service;

import cn.js.sangu.unitStore.common.exception.ServiceException;
import cn.js.sangu.unitStore.dto.FileListDTO;
import cn.js.sangu.unitStore.entity.Project;
import cn.js.sangu.unitStore.mapper.ProjectMapper;
import cn.js.sangu.unitStore.utils.TokenUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

@Slf4j
@Service
public class ProjectService extends ServiceImpl<ProjectMapper, Project> {

    public Project saveInfo(Project dto) {
        Project project = spliceProjectInfo(dto);
        project.setCreator(Objects.requireNonNull(TokenUtils.getCurrentUser()).getId());
        if (!super.save(project)){
            throw new ServiceException("保存失败！请联系管理员");
        }
        return project;
    }

    public void updateInfo(Project dto) {
        Project project = spliceProjectInfo(dto);
        project.setModifier(Objects.requireNonNull(TokenUtils.getCurrentUser()).getId());
        if (!super.updateById(project)){
            throw new ServiceException("更新失败！请联系管理员");
        }
    }

    private Project spliceProjectInfo(Project dto){
        /**
         * 参考DistributeService
         * 因为Project的前端已经处理好了AttacheName和AttacheIds
         * 且本模块不打算做统计附件个数的字段，所以只存FileListJson就好了
         */
        List<FileListDTO> fileList = dto.getFileList();
        if (null != fileList){
            dto.setFileListJson(new ObjectMapper().valueToTree(fileList));
        }
        return dto;
    }
}
